package com.shop.shopserver.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shoppojo.dto.SmsSendDTO;
import com.shop.shoppojo.dto.TemplateParamDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.shop.shopcommon.constant.RabbitMQConstant.SMS_SEND_REQUEST_QUEUE;

/**
 *  监听短信相关消息
 */
@Slf4j
@Component
public class ListenSmsMessageHeader {
    @Autowired
    private Client aliyunSmsClient;
    @Autowired
    private com.shop.shopcommon.properties.AliSmsProperties aliSmsProperties;

    /**
     * 监听短信发送请求消息
     * @param message
     */
    @RabbitListener(queues = SMS_SEND_REQUEST_QUEUE)
    public void listenSmsSendRequestMessage(String message) throws Exception {
        // 解析消息
        SmsSendDTO smsSendDTO = JSON.parseObject(message, SmsSendDTO.class);
        // 填充短信模板
        TemplateParamDTO templateParamDTO = new TemplateParamDTO(smsSendDTO.getCode());
        String jsonString = JSON.toJSONString(templateParamDTO);

        // 发送短信
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(aliSmsProperties.getSignName())
                .setTemplateCode(aliSmsProperties.getTemplateCode())
                .setPhoneNumbers(smsSendDTO.getPhone())
                .setTemplateParam(jsonString);
        aliyunSmsClient.sendSms(sendSmsRequest);

        // 打印日志
        log.info("短信发送成功：" + message);
    }
}
